import {onMounted} from "vue";

/** 验证结果 */
export type SliderValidatorResult = {
  /** 验证结果，0：验证成功。2：用户主动关闭验证码。 */
  ret: number

  /** 验证成功的票据，当且仅当 ret = 0 时 ticket 有值。 */
  ticket: string

  /** 验证码应用ID */
  CaptchaAppId: string

  /** 自定义透传参数 */
  bizState: any

  /** 本次验证的随机串，请求后台接口时需带上 */
  randstr: string
}

/**
 # TencentCaptcha 的配置参数

 - res（用户主动关闭验证码）= `{ret: 2, ticket: null}`
 - res（验证成功） = `{ret: 0, ticket: string, randstr: string}`
 - res（客户端出现异常错误 仍返回可用票据） = `{ret: 0, ticket: string, randstr: string,  errorCode: number, errorMessage: string}`
 */
export type TencentCaptchaOptions = {

  /** 自定义透传参数，业务可用该字段传递少量数据，该字段的内容会被带入callback回调的对象中 */
  bizState?: any

  /** 开启自适应深夜模式 */
  enableDarkMode?: boolean

  /**
   # sdkOpts
   示例 `{"width": 140, "height": 140}`

   注: 只在移动端原生 webview 调用时传入，为设置的验证码元素 loading 弹框大小
   */
  sdkOpts?: { width: number; height: number }

  /**
   # ready
   验证码加载完成的回调, 回调参数为验证码实际的宽高。
   手机原生端可根据此值设置弹框大小。
   */
  ready?: (p: { sdkView: { width: number; height: number } }) => any
}

/** 腾讯验证码 */
declare class TencentCaptcha {
  constructor(appId: string, callback: (p: SliderValidatorResult) => any, options?: TencentCaptchaOptions)
  show(...params: any): any
}

// 复刻 Promise 下的 Resolve 和 Reject 类型
type Resolve = (value: SliderValidatorResult | PromiseLike<SliderValidatorResult>) => void
type Reject = (reason?: any) => void

// 返回值方法
export type ApplySlider = () => Promise<SliderValidatorResult>

/**
 腾讯滑块验证器
 **/
export function sliderVerification(options?: TencentCaptchaOptions): ApplySlider {
  if (!TencentCaptcha) throw new Error('TencentCaptcha is not defined')

  let promise = {} as { resolve: Resolve; reject: Reject }
  let slider: TencentCaptcha
  onMounted(() => {

    debugger
    console.log(slider)
  })

  return () => {
    return new Promise<SliderValidatorResult>((resolve, reject) => {

      slider = new TencentCaptcha(
        // App Id
        "196396370",
        // Callback
        (res: SliderValidatorResult) => {
          promise.resolve(res)
        },
        { needFeedBack: false } as TencentCaptchaOptions
      )

      slider.show()
      promise = { resolve, reject }
    })
  }
}
